package com.lam.dormitory.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lam.dormitory.entity.Permission;
import com.lam.dormitory.entity.Role;
import com.lam.dormitory.entity.User;
import com.lam.dormitory.entity.UserRole;
import com.lam.dormitory.service.*;
import com.lam.dormitory.util.ResponseTemplate;
import com.lam.dormitory.util.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lam
 * @since 2019-12-20
 */
@Api(tags = "角色接口")
@RestController
@RequestMapping("/role")
public class RoleController {
    private static final Logger logger = LoggerFactory.getLogger(RoleController.class);

    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private IRolePermissionService rolePermissionService;

    /*新增角色*/
    @ApiOperation(value = "新增角色", notes = "新增角色")
    @PostMapping("/add")
    @RequiresRoles(value = {"admin", "superadmin"}, logical = Logical.OR)
//    @RequiresPermissions("role:add")
    public ResponseTemplate addRole(Role addRole) {
        if (null != roleService.selectRoleByName(addRole.getName())) {
            return new ResponseTemplate(500, "角色名已经存在");
        }
        addRole.setStatus(1);
        Date date = new Date();
        addRole.setCreateTime(date);
        addRole.setUpdateTime(date);
        boolean a = roleService.save(addRole);
        if (a) {
            return new ResponseTemplate(200, "添加角色成功");
        } else {
            return new ResponseTemplate(500, "添加角色失败");
        }
    }

    /*删除角色*/
    @ApiOperation(value = "删除角色", notes = "根据roleId删除角色")
    @PostMapping("/delete")
    @RequiresRoles(value = {"admin", "superadmin"}, logical = Logical.OR)
//    @RequiresPermissions("role:delete")
    public ResponseTemplate deleteRole(Long roleId) {
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UserRole::getRoleId, roleId);
        boolean a = userRoleService.remove(wrapper);
//        if (userRole != null) {
//            return new ResponseTemplate(500, "删除失败,该角色下存在用户");
//        }
        QueryWrapper<Role> wrapper1 = new QueryWrapper<>();
        wrapper1.lambda().eq(Role::getRoleId, roleId);
        boolean b = roleService.remove(wrapper1);
        if (a||b) {
            return new ResponseTemplate(200, "删除角色成功");
        } else {
            return new ResponseTemplate(500, "删除角色失败");
        }
    }

    /*编辑角色*/
    @ApiOperation(value = "编辑角色", notes = "编辑角色")
    @PostMapping("/edit")
//    @RequiresPermissions("role:edit")
    @RequiresRoles(value = {"admin", "superadmin"}, logical = Logical.OR)
    public ResponseTemplate editRole(Role role) {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Role::getRoleId, role.getRoleId());
        Date date = new Date();
        role.setUpdateTime(date);
        boolean b = roleService.update(role, wrapper);
        if (b) {
            return new ResponseTemplate(200, "编辑角色成功");
        } else {
            return new ResponseTemplate(500, "编辑角色失败");
        }
    }

    /*角色列表数据*/
    @ApiOperation(value = "角色列表数据", notes = "可按条件(roleId,name)查询角色列表数据,pageNum 默认为 1，pageSize默认为 0")
    @PostMapping("/list")
//    @RequiresPermissions("role:list")
    @RequiresRoles(value = {"admin", "superadmin"}, logical = Logical.OR)
    public ResponseTemplate pageRoles(Role role) {
        List<Role> roleList = roleService.selectByRole(role);
        if (null == roleList) {
            return new ResponseTemplate(500, "获取用户列表数据失败", null);
        } else {
            return new ResponseTemplate(200, "获取用户列表数据成功", roleList);
        }
    }

    /*分配权限*/
    @ApiOperation(value = "分配权限", notes = "根据roleId，permissionIdStr分配权限")
    @PostMapping("/assign/permission")
//    @RequiresPermissions("role:assignPerms")
    @RequiresRoles(value = {"admin", "superadmin"}, logical = Logical.OR)
    public ResponseTemplate assignRole(Long roleId, @RequestParam(value = "permissionIds") List<Long> permissionIds) {
        ResponseTemplate responseTemplate = roleService.addAssignPermission(roleId, permissionIds);
        /*重新加载角色下所有用户权限*/
        List<User> users = userService.selectByRoleId(roleId);
        if (users.size() > 0) {
            for (User user : users) {
                ShiroUtils.deleteCache(user.getUsername(), false);
            }
        }
        return responseTemplate;
    }

    /**
     * 查询分配权限
     * @param roleId
     * @return
     */
    @ApiOperation(value = "查询分配权限", notes = "根据roleId查询分配权限")
    @PostMapping("/assign/permission/list")
//    @RequiresPermissions("role:assignPerms")
    @RequiresRoles(value = {"admin", "superadmin"}, logical = Logical.OR)
    public ResponseTemplate selectAssignRole(Long roleId) {
        List<Permission> permissionList = permissionService.selectPermissionByRoleId(roleId);
        return new ResponseTemplate(200, "查询成功", permissionList);
    }

    /**
     * 删除角色内的权限
     * @param permissionId
     * @return
     */
    @ApiOperation(value = "删除角色内的权限", notes = "根据roleId,permissionId删除角色内的权限")
    @PostMapping("/assign/permission/delete")
//    @RequiresPermissions("role:assignPerms")
    @RequiresRoles(value = {"admin", "superadmin"}, logical = Logical.OR)
    public ResponseTemplate deletePerm(Long roleId,Long permissionId){
        int subPermsByPermissionIdCount = permissionService.selectSubPermsByPermissionId(permissionId);
        Map<String,Object> map = new HashMap<>();
        if (subPermsByPermissionIdCount > 0) {
            List<Permission> permissionLists = permissionService.selectPermsAndChildren(permissionId);
            for (Permission permissionList : permissionLists) {
                map.put("role_id",roleId);
                map.put("permission_id",permissionList.getPermissionId());
                rolePermissionService.removeByMap(map);
            }
        }
        map.put("role_id",roleId);
        map.put("permission_id",permissionId);
        boolean b = rolePermissionService.removeByMap(map);
        if (b) {
            return new ResponseTemplate(200,"删除成功");
        }
        return new ResponseTemplate(500,"删除失败");
    }
}
